<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>websocket test!</title>
</head>

<body>
  <p>发送：<span class="clog">--</span></p>
  <p>接收：<span class="slog">--</span></p>
  <input class="msg" type="text" />
  <button id="send">发送</button>
  <hr>
  <p>
    <button id="open">打开连接</button>
    <button id="close">关闭连接</button>
  </p>
  <script>
    let ws
    // 初始化ws
    let initWs = () => {
      ws = new WebSocket('wss://echo.websocket.org');
      // 连接成功
      ws.onopen = function (e) {
        console.log(e)
      }
      // 接收消息
      ws.onmessage = function (e) {
        console.log(e)
        document.querySelector('.slog').innerText = e.data

      }

      // 关闭连接
      ws.onclose = function (e) {
        console.log(e)
      }
    }

    initWs()


    // 发送消息
    document.getElementById('send').onclick = function (e) {
      let clog = document.querySelector('.msg').value
      document.querySelector('.clog').innerText = clog
      ws.send(clog)
      document.querySelector('.msg').value = ''
    }

    // 关闭连接
    document.querySelector('#close').onclick = function () {
      ws.close()
    }

    // 打开连接
    document.querySelector('#open').onclick = function () {
      initWs()
    }
  </script>
</body>

</html>